﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EximDemo.Common;
using System.Text;

namespace EximDemo.Models
{
    public class BizExport
    {
        private EximModelDataContext _context = new EximModelDataContext();
        public string FileName { get; set; }

        public BizExport()
        {
            this.FileName = GenerateDistinguishFileName();
        }

        public BizExport(string filename)
        {
            this.FileName = filename;
        }

        public string RenderExportData()
        {
            if (string.IsNullOrEmpty(this.FileName))
            {
                throw new Exception("Filename is empty.");
            }
            
            //debug
            DateTime start = DateTime.Now;

            StringBuilder sb = new StringBuilder();

            var query = from prs in _context.productrangestatus
                        select prs;

            foreach (productrangestatus p in query)
            {
                sb.Append(CommonUtils.CSVFieldFormat(p.storeId.ToString()));
                sb.Append(",");
                sb.Append(CommonUtils.CSVFieldFormat(p.productId.ToString()));
                sb.Append(",");
                sb.Append(CommonUtils.CSVFieldFormat(p.status));
                sb.Append(",");
                sb.Append(CommonUtils.CSVFieldFormat(p.range));
                sb.Append(Environment.NewLine);
            }

            //debug
            DateTime end = DateTime.Now;
            Debug.Print("Executed duration: " + (end - start).ToString());
            
            return sb.ToString();            
        }

        public static string GenerateDistinguishFileName()
        {
            return string.Format("Export_{0}.csv", DateTime.Now.ToString("yyyyMMddHHmmss"));
        }
    }
}